package nio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author dylan
 * @version 0.0.0.1
 * description
 * @date: 2024/4/10 21:02
 */
public class ChannelUtils {

    public static Map<String, SocketChannel> CHANNEL_MAP = new ConcurrentHashMap<>();

    public static void sendMsg(){
        // 使用 Iterator 遍历 CHANNEL_MAP，并删除未连接的 SocketChannel
        Iterator<Map.Entry<String, SocketChannel>> iterator = CHANNEL_MAP.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, SocketChannel> entry = iterator.next();
            String clientId = entry.getKey();
            SocketChannel socketChannel = entry.getValue();

            if (!socketChannel.isOpen()) {
                // 如果连接已关闭，则从 CHANNEL_MAP 中删除对应的键值对
                iterator.remove();
                System.out.println("Closed connection for client: " + clientId);
            } else {
                System.out.println("Client ID: " + clientId + ", SocketChannel: " + socketChannel);
                // 在这里可以进行其他逻辑处理
                try {
                    socketChannel.write(ByteBuffer.wrap(new String("来自服务端的通知").getBytes(StandardCharsets.UTF_8)));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
